package com.iuie.ns.datum.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.system.service.code.ISysCodeInfoService;
import com.iuie.ns.system.vo.code.SysCodeInfoVO;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.iuie.ns.datum.mapper.BlogMapper;
import com.iuie.ns.datum.service.IBlogSolrService;
import com.iuie.ns.datum.vo.BlogInfoVO;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.utils.WebUtils;

@Service("blogSolrService")
public class BlogSolrServiceImpl implements IBlogSolrService{

	private static final Logger logger = LoggerFactory.getLogger(BlogSolrServiceImpl.class);

	@Resource
	private BlogMapper blogMapper;

	@Resource
	private HttpSolrClient httpSolrClient;

	@Resource
	private ISysCodeInfoService codeInfoService;

	@Override
	public List<BlogInfoVO> findByContextOrName(String key, String search) throws SolrServerException, IOException {
		List<BlogInfoVO> blogInfoVOList = new ArrayList<BlogInfoVO>();

		if(StringUtils.isBlank(search)) return blogInfoVOList;
		//根据标题在数据库查询
		List<BlogInfoVO> blogInfoVOs = blogMapper.findByBlogName(search);
		blogInfoVOList.addAll(blogInfoVOs);
		//不使用索引查询
		if(!getSolrStatus()){
			return blogInfoVOList;
		}
		//根据内容在solr索引中查询
		String query = new StringBuilder(key).append(":").append(search).toString();
		SolrQuery  params = new SolrQuery(query);
		//设置查询高亮
		params.setHighlight(true);
		params.addHighlightField("MD_CONTENT");
		params.setHighlightSimplePre("<span style='color:red'>");
		params.setHighlightSimplePost("</span>");

		QueryResponse  response = httpSolrClient.query(params);
		SolrDocumentList list =response.getResults();
		Map<String,Map<String,List<String>>> map = response.getHighlighting();
		for(int i=0; i<list.size(); i++){
			Long id = getId(list.get(i));
			if(id != null){
				BlogInfoVO blogInfoVO = blogMapper.findById(id);
				if(blogInfoVO != null){
					blogInfoVO.setText(getText(list.get(i),map));
					blogInfoVOList.add(blogInfoVO);
				}
			}
		}
		return blogInfoVOList;
	}

	@Override
	public void deleteBlogFileIndex(String deleteCondition) throws Exception {
		if(!getSolrStatus()){
			return;
		}
		httpSolrClient.deleteByQuery(deleteCondition);
		httpSolrClient.commit();
	}


	private boolean getSolrStatus(){
		List<SysCodeInfoVO> blogTypes = codeInfoService.findByCodeTypeId("solrStatus", 1);
		for(SysCodeInfoVO sysCodeInfoVO : blogTypes){
			if(Integer.valueOf(sysCodeInfoVO.getCodeInfoValue() ) == 1){
				return true;
			}
		}
		return false;
	}


	/**
	 * 创建博客索引
	 * @param blogInfo
	 */
	public void createSolrIndex(BlogInfoVO blogInfo) {
		if(!getSolrStatus() || blogInfo == null){
			return;
		}
		SolrInputDocument document = new SolrInputDocument();
		document.addField("blog_id", blogInfo.getBlogId());
		document.addField("create_time", blogInfo.getCreateTime());
		document.addField("author", blogInfo.getAuthor());
		document.addField("blog_name", blogInfo.getBlogName());
		document.addField("remarks", blogInfo.getBlogType());
		document.addField("blog_type", blogInfo.getBlogType());
		document.addField("MD_CONTENT", blogInfo.getMdContent());
		try {
			httpSolrClient.add(document);
			httpSolrClient.commit();
		} catch (Exception e) {
			logger.error("创建文件索引失败", e);
			throw new ServiceException("创建文件索引失败");
		}
	}

	private String getText(SolrDocument solrDocument,Map<String,Map<String,List<String>>> maps){
		String blogId = (String) solrDocument.get("blog_id");
		if(StringUtils.isBlank(blogId)) return null;
		Map<String,List<String>> mapList = maps.get(blogId);
		if(mapList == null || mapList.size() == 0) return null;
		String result = mapList.get("MD_CONTENT").get(0);
		return result;
	}

	private Long getId(SolrDocument solrDocument) {
		String blogId = (String) solrDocument.get("blog_id");
		if(WebUtils.isURL(blogId)) return null;
		return new Long(blogId);
	}

}
